﻿using System;
using System.IO;
using System.IO.Compression;
using System.Text;
using Avalonia.Controls;
using Avalonia.Interactivity;

namespace DevHub.WindowsApp.Pages.Encode;

public partial class GZipEncodeView : UserControl
{
    public GZipEncodeView()
    {
        InitializeComponent();
    }

    private static byte[] Decompress(byte[] bytes)
    {
        using var compressStream = new MemoryStream(bytes);
        using var zipStream = new GZipStream(compressStream, CompressionMode.Decompress);
        using var resultStream = new MemoryStream();
        zipStream.CopyTo(resultStream);
        return resultStream.ToArray();
    }

    private static byte[] Compress(byte[] rawData)
    {
        var ms = new MemoryStream();
        var zipStream = new GZipStream(ms, CompressionMode.Compress, true);
        zipStream.Write(rawData, 0, rawData.Length);
        zipStream.Close();
        return ms.ToArray();
    }

    private void EncryptTextChanged(object? sender, TextChangedEventArgs e)
    {
        if (!Switch.IsChecked!.Value)
        {
            if (string.IsNullOrEmpty(EncryptBox.Text) || EncryptBox.Text.Length == 0)
            {
                DecryptBox.Text = "";
                return;
            }

            DecryptBox.Text = Convert.ToBase64String(Compress(Encoding.UTF8.GetBytes(EncryptBox.Text)));
        }
        else
        {
            try
            {
                if (string.IsNullOrEmpty(EncryptBox.Text) || EncryptBox.Text.Length == 0)
                {
                    DecryptBox.Text = "";
                    return;
                }

                DecryptBox.Text = Convert.ToBase64String(Decompress(Convert.FromBase64String(EncryptBox.Text)));
            }
            catch
            {
                DecryptBox.Text = "该文本不是由GZip压缩的文本而来的";
            }
        }
    }

    private void CopyDecryptClick(object? sender, RoutedEventArgs e)
    {
        if (string.IsNullOrEmpty(DecryptBox.Text)) return;
        var top = TopLevel.GetTopLevel(this);
        top?.Clipboard?.SetTextAsync(DecryptBox.Text);
    }

    private void ClearDecryptClick(object? sender, RoutedEventArgs e)
    {
        DecryptBox.Text = "";
    }

    private void CopyEncryptClick(object? sender, RoutedEventArgs e)
    {
        if (string.IsNullOrEmpty(EncryptBox.Text)) return;
        var top = TopLevel.GetTopLevel(this);
        top?.Clipboard?.SetTextAsync(EncryptBox.Text);
    }

    private void ClearEncryptClick(object? sender, RoutedEventArgs e)
    {
        EncryptBox.Text = "";
    }

    private void ToggleIsCheckedChanged(object? sender, RoutedEventArgs e)
    {
        (EncryptBox.Text, DecryptBox.Text) = (DecryptBox.Text, EncryptBox.Text);
    }
}